<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2.X响应式原理</title>
</head>

<body>
  <script>
    // 模拟Vue中的data选项
    let data = {
      name: 'Tom',
      age: 18,
    }
    // 实现一个响应式函数
    function observerProxy(obj) {
      let handler = {
        get(target, key, receiver) {
          console.log('获取：' + key)
          // 如果是对象，就递归添加 proxy 拦截
          if (typeof target[key] === 'object' && target[key] !== null) {
            return new Proxy(target[key], handler)
          }
          return Reflect.get(target, key, receiver)
        },
        set(target, key, value, receiver) {
          console.log(key + "-数据改变了")
          return Reflect.set(target, key, value, receiver)
        }
      }
      return new Proxy(obj, handler)
    }

    let obj = observerProxy(data);
    obj.name = 'Lily'
    console.log(obj.name);
    obj.age = 20
    console.log(obj.age);
  </script>
</body>

</html>